// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';
// const isProduction = true;
/**
 * localStorage 的基础操作封装
 */
import {decrypt, encrypt} from '@/utils/jsencrypt';

function setStorageL(key: string, value: any) {
    if (isProduction) {
        localStorage.setItem(key, encrypt(JSON.stringify(value)));
    } else {
        localStorage.setItem(key, JSON.stringify(value));
    }
}

function getStorageL(key: string) {
    const item = localStorage.getItem(key);
    if (item != null) {
        if (isProduction) {
            try {
                return JSON.parse(decrypt(item));
            } catch (e) {
                removeStorageL(key);
                return null;
            }
        } else {
            return JSON.parse(item);
        }
    }
    return null;
}

function removeStorageL(key: string) {
    localStorage.removeItem(key);
}

/**
 * localStorage 的基础操作封装
 */
function setStorageS(key: string, value: any) {
    if (isProduction) {
        sessionStorage.setItem(key, encrypt(JSON.stringify(value)));
    } else {
        sessionStorage.setItem(key, JSON.stringify(value));
    }
}

function getStorageS(key: string) {
    const item = sessionStorage.getItem(key);
    if (item != null) {
        if (isProduction) {
            try {
                return JSON.parse(decrypt(item));
            } catch (e) {
                removeStorageL(key);
                return null;
            }
        } else {
            return JSON.parse(item);
        }
    }
    return null;
}

function removeStorageS(key: string) {
    sessionStorage.removeItem(key);
}

/**
 * 清空所有
 */
function clearStore() {
    sessionStorage.clear();
    localStorage.clear();
}

const CONST = !isProduction ? {
    // token key
    token: 'token',
    router: 'router',
    avatar: 'avatar',
    collapse: 'collapse',
    projectInfo: 'projectInfo',
    addRoutes: 'addRoutes',
    userInfo: 'userInfo',
    name: 'name',
    logoSrc: 'logoSrc',
    permission: 'permission',
} : {
    token: 'a',
    router: 'b',
    avatar: 'c',
    collapse: 'd',
    projectInfo: 'e',
    addRoutes: 'f',
    userInfo: 'g',
    name: 'h',
    logoSrc: 'i',
    permission: 'j',
};

export default {
    setStorageL,
    getStorageL,
    removeStorageL,
    setStorageS,
    getStorageS,
    removeStorageS,
    clearStore,
    CONST,
};
